var express = require('express');
var router = express.Router();
var connection = require('../connect');

// 获取所有旅舍信息
router.get('/lvs', (req, res, next) => {
  connection.query('select * from qn_yuding', (err, r) => {
    if (err) {
      return next(err);
    }
    console.log(r);
    res.send({
      code: 200,
      msg: '成功',
      data: r,
    });
  });
});
router.post('/lvsearch', (req, resp) => {
  let { name } = req.body;
  // 执行模糊查询
  connection.query('select * from qn_yuding where title like ?', [`%${name}%`], (err, r) => {
    if (err) {
      return next(err);
    }
    // 将结果封装，返回给客户端
    resp.send({
      code: 200,
      msg: '成功',
      data: r,
    });
  }
  );
});
// 是否收藏
router.get('/collect', (req, resp) => {
  let { title, uid } = req.query;
  // 执行查询
  connection.query('select * from qn_collect where title=? and uid=?', [title, uid], (err, r) => {
    if (err) {
      return next(err);
    }
    // 将结果封装，返回给客户端
    resp.send({
      code: 200,
      data: r
    });
  }
  );
});

// 加入收藏
router.get('/tocollect', (req, resp) => {
  let { title, uid, area } = req.query;
  const time = parseInt(new Date().getTime() / 1000)
  // 执行插入
  connection.query('INSERT INTO qn_collect(title,uid,time,area) VALUES(?,?,?,?)', [title, uid, time, area], (err, r) => {
    if (err) {
      return next(err);
    }
    // 将结果封装，返回给客户端
    resp.send({
      code: 200,
      data: r
    });
  }
  );
});



// 删除收藏
router.post('/delcollect', (req, resp) => {
  let { cid } = req.body;
  // 执行插入
  connection.query('delete from qn_collect where cid=?', [cid], (err, r) => {
    if (err) {
      return next(err);
    }
    // 将结果封装，返回给客户端
    resp.send({
      code: 200,
      data: r
    });
  }
  );
});
// 通过用户id 查询所有收藏
router.get('/allcollect', (req, resp) => {
  let { uid } = req.query;
  // 执行查询
  connection.query('select * from qn_collect where uid=?', [uid], (err, r) => {
    if (err) {
      return next(err);
    }
    // 将结果封装，返回给客户端
    resp.send({
      code: 200,
      data: r
    });
  }
  );
});
module.exports = router;
